package io.jee.caisan.weixin.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.constant.WxPayConstants.ResultCode;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;

import io.jee.alaska.util.IpUtils;
import io.jee.alaska.util.Result;
import io.jee.caisan.member.client.service.RemoteBalanceService;
import io.jee.caisan.member.domain.BalanceCaidouInpour;
import io.jee.caisan.member.domain.MemberBalance;
import io.jee.caisan.weixin.config.ConfigProperties;
import io.jee.caisan.weixin.config.Constant;
import io.jee.caisan.weixin.config.SessionManager;
import io.jee.caisan.weixin.config.UrlManager;
import io.jee.caisan.weixin.domain.Member;
import io.jee.caisan.weixin.domain.SysActivity;
import io.jee.caisan.weixin.domain.SysConfig;
import io.jee.caisan.weixin.service.MemberService;
import io.jee.caisan.weixin.service.PayService;
import io.jee.caisan.weixin.service.SysActivityService;
import io.jee.caisan.weixin.service.SysConfigService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;

@Controller
@RequestMapping("/pay")
public class PayController {
	
	@Resource
	private RemoteBalanceService remoteBalanceService;
	
	@Resource
	private SessionManager sessionManager;
	
	@Resource
	private MemberService memberService;
	
	@Resource
	private UrlManager urlManager;
	
	@Resource
	private WxMpService wxMpService;
	
	@Resource
    private PayService payService;
	
	@Resource
	private WxPayService wxPayService;
	
	@Resource
	private ConfigProperties configProperties;
	
	@Resource
	private SysConfigService sysConfigService;
	
	@Resource
	private SysActivityService sysActivityService;

	/**
	 * 充值-页面
	 * @param model
	 * @param request
	 * @return
	 * @throws WxErrorException
	 */
	@GetMapping(value = {"/index"})
	public String index(Model model, HttpServletRequest request) throws WxErrorException {
		Member member = sessionManager.getSessionMember(request);
		MemberBalance memberBalance = remoteBalanceService.getBalance(member.getMid());
		model.addAttribute("memberBalance", memberBalance);
		
		SysConfig sysConfig = sysConfigService.findOneByType(SysConfig.TYPE_0);
		model.addAttribute("sysConfig", sysConfig);
		
		SysActivity sa = sysActivityService.findOneByTypeAndCode(SysActivity.TYPE_2, Constant.PAY_CODE);
		if(sa != null) {
			Date now = Calendar.getInstance().getTime();
			if(now.after(sa.getStartTime()) && now.before(sa.getEndTime())) {
				model.addAttribute("content", Double.valueOf(sa.getContent()));
			}
		}
		
		return "pay/index";
	}
	
	/**
	 * 充值结果-页面
	 * @param model
	 * @param request
	 * @param orderId
	 * @param status
	 * @return
	 */
	@GetMapping(value = {"/result"})
	public String result(Model model, HttpServletRequest request, String orderId, String status) {
		BalanceCaidouInpour inpour = remoteBalanceService.getCaidouInpour(orderId);
		model.addAttribute("inpour", inpour);
		model.addAttribute("status", status);
		return "pay/result";
	}
	
	/**
	 * 微信充值请求
	 * @param model
	 * @param request
	 * @param caidou
	 * @return
	 * @throws ParseException
	 */
	@PostMapping(value = { "/create/pay" })
	@ResponseBody
	public Result<?> createPay(Model model, HttpServletRequest request, BigDecimal caidou) {
		String openid = sessionManager.getSessionOpenid(request);
		
		BigDecimal money = caidou;
		SysActivity sa = sysActivityService.findOneByTypeAndCode(SysActivity.TYPE_2, Constant.PAY_CODE);
		if(sa != null) {
			Date now = Calendar.getInstance().getTime();
			if(now.after(sa.getStartTime()) && now.before(sa.getEndTime())) {
				money = money.multiply(new BigDecimal(sa.getContent()));//活动折扣计算, content填写折扣率
			}
		}
		
		return payService.createMpPay(openid, caidou, money, urlManager.payNotify(), IpUtils.getIpAddr(request));
	}
	
	/**
	 * 微信充值异步回调
	 * @param model
	 * @param xmlData
	 * @return
	 */
	@RequestMapping(value = { "/notify" })
	@ResponseBody
	public String notify(Model model, @RequestBody String xmlData) {
		try {
			WxPayOrderNotifyResult notify = wxPayService.parseOrderNotifyResult(xmlData);
			if(notify.getReturnCode().equals(ResultCode.SUCCESS)) {
				if(ResultCode.SUCCESS.equals(notify.getResultCode())) {
					String orderNo = notify.getOutTradeNo();
				    remoteBalanceService.inpourSuccess(orderNo);
				    return WxPayNotifyResponse.success("OK");
				}
			}
		} catch (WxPayException e) {
			e.printStackTrace();
		}
		return WxPayNotifyResponse.fail("ERROR");
	}
}
